package com.ocean.proxy.api.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.inveno.util.CollectionUtils;
import com.ocean.core.common.system.SystemContext;
import com.ocean.core.common.threadpool.Parameter;
import com.ocean.persist.api.proxy.AdPullException;
import com.ocean.persist.api.proxy.xunfei.XunfeiAdPullParams;
import com.ocean.persist.api.proxy.xunfei.XunfeiAdPuller;
import com.ocean.persist.api.proxy.xunfei.XunfeiAdResponse;
import com.ocean.persist.api.proxy.xunfei.XunfeiDebug;
import com.ocean.persist.api.proxy.xunfei.XunfeiNativeAd;
import com.ocean.persist.api.proxy.xunfei.XunfeiNativeAdDetails;
import com.ocean.persist.api.proxy.xunfei.XunfeiVideoAd;
import com.ocean.persist.common.ProxyConstants;
import com.ocean.persist.model.proxy.DSPPosition;
import com.ocean.proxy.api.base.AbstractAdSupplier;
import com.ocean.proxy.api.helper.InvenoIdGenerator;
import com.ocean.proxy.thrift.entity.AdContent;
import com.ocean.proxy.thrift.entity.AdImg;
import com.ocean.proxy.thrift.entity.AdMutiAction;
import com.ocean.proxy.thrift.entity.AdRecomReply;
import com.ocean.proxy.thrift.entity.AdRecomReq;
import com.ocean.proxy.thrift.entity.AdSpaceType;
import com.ocean.proxy.thrift.entity.AdUserInfo;
import com.ocean.proxy.thrift.entity.UserAdSpaceAttri;
import com.ocean.core.common.threadpool.workthread.AsynAbstractTask;

@Component(value="xunfeiAdSupplier")
public class XunfeiAdSupplier  extends AbstractAdSupplier{
    @Autowired
	private XunfeiAdPuller XunfeiAdPuller;
	public AdRecomReply invoke(InvokeAttribute attribute) throws AdPullException {
		AdRecomReq adreq = attribute.getAdreq();
		DSPPosition positionInfo = attribute.getDspPosition();
		XunfeiAdPullParams params = parseParams(adreq, positionInfo);
		XunfeiAdResponse response = (XunfeiAdResponse) XunfeiAdPuller.api(params,adreq.getHash(),String.valueOf(adreq.getUserAdSpaceAttri().getAdSpaceId()));
		return parseResult(response);
	}
	
	private XunfeiAdPullParams parseParams(AdRecomReq adreq, DSPPosition posInfo)
			 throws AdPullException {
		
		// 广告属性
		UserAdSpaceAttri attri = adreq.getUserAdSpaceAttri();
		AdUserInfo userInfo = adreq.getUserinfo();
		
		XunfeiAdPullParams params = new XunfeiAdPullParams();
		params.setAppid(posInfo.getText1());
		params.setAppname(adreq.getApp());
		params.setAdid(userInfo.getAdid());
		params.setAppver(adreq.getVersion());
		// 讯飞广告位id
		params.setAdunitid(posInfo.getPos());
		if(StringUtils.isNotEmpty(userInfo.getDensity())){
			params.setDensity(userInfo.getDensity());
		}
		//params.setDensity("1");
		// // -1-未知 0-phone 1-pad 2-pc 3-tv 4-wap
		params.setDevicetype(0);
		params.setTramaterialtype("json");
		// 开屏
		short isboot;
		// 请求广告类型
		if(AdSpaceType.OPENING.equals(attri.getSpaceType())){
			isboot = 1;
		}else{
			isboot = 0;
		}
		params.setIsboot(isboot);
		params.setAdh(attri.getSpaceHeight());
		params.setAdw(attri.getSpaceWidth());
		params.setImei(userInfo.getImei());
		params.setIp(userInfo.getClient_ip());
		params.setOs(userInfo.getOs());
		params.setOsv(userInfo.getOsversion());
		params.setUa(userInfo.getUa());
		params.setLan("zh-CN");
		params.setMac(userInfo.getMac());
		params.setVendor(userInfo.getBrand_name());
		params.setModel(userInfo.getPhonemodel());
		params.setPkgname(posInfo.getText2());
		// 竖屏
		params.setOrientation((short)1);
		// 设备宽高
		params.setDvh(userInfo.getDevice_height());
		params.setDvw(userInfo.getDevice_width());
		params.setTs(String.valueOf(System.currentTimeMillis()));
		params.setBatch_cnt(1);
		// 网络运营商 46000中国移动
		String op=mobiles.get(userInfo.getMobile());
		params.setOperator(StringUtils.isEmpty(op)?"46000":op);
		// 2 wifi
		params.setNet(String.valueOf(2));
		XunfeiDebug debug = new XunfeiDebug();
		debug.setAction_type(0);
		debug.setLanding_type(0);
		params.setDebug(debug);
		return params;
	}
	
	private AdRecomReply parseResult(XunfeiAdResponse response)
			throws AdPullException {
		
		if(response == null){
			return null;
		}
		Class<?> clazz = response.getClass();
		if(XunfeiNativeAd.class.isAssignableFrom(clazz)){
			
			return parseNativeAd((XunfeiNativeAd)response);
		}
		else if(XunfeiVideoAd.class.isAssignableFrom(clazz)){
			return parseVideoAd((XunfeiVideoAd)response);
		}
		else{
			throw new AdPullException("无法解析的结果");
		}
	}
	
	private AdRecomReply parseNativeAd(XunfeiNativeAd response){
		
		// 返回对象
		AdRecomReply recomReply = new AdRecomReply();
		recomReply.setStatus(status);
		
		List<XunfeiNativeAdDetails> details = response.getBatch_ma();
		if(details == null || details.isEmpty()){
			return null;
		}
		// 只返回一条
		XunfeiNativeAdDetails detail = details.get(0);
		// 广告内容
		AdContent content = new AdContent();
		String title = detail.getTitle();
		// 标题不能为null对象
		if(StringUtils.isEmpty(title)){
			title = defTitle;
		}
		// 类型
		AdMutiAction action = new AdMutiAction();
		// 内容类型1表示链接推广,2表示应用推广,3未使用 4表示电话推广
		int actType=ACTION_WEB;

		action.setGuideTitle(title);
		content.setGuideTitle(title);
		content.setMarketTitle(title);
		content.setContent(detail.getSub_title());
		//content.setAdId(InvenoIdGenerator.genThirdDspId(SystemContext.getDynamicPropertyHandler().getInt(ProxyConstants.PROXY_SERVER_NODE_INDEX,100)));

		action.setLinkurl(detail.getLanding_url());
		
		List<AdImg> imgs = new ArrayList<AdImg>();
		// 广告图片
		String imgurl = detail.getImage();
		if(!StringUtils.isEmpty(imgurl)){
			AdImg img = new AdImg();
			img.setSrc(imgurl);
			imgs.add(img);
		}
		
		String icon = detail.getIcon();
		if(!StringUtils.isEmpty(icon)){
			if(imgs.isEmpty()){
				AdImg img = new AdImg();
				img.setSrc(icon);
				imgs.add(img);
			}
			else{
				content.setCpIcon(icon);
				action.setCpIcon(icon);
			}
		}
		content.setImglist(imgs);
		

		
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		// 点击监测
/*		List<String> click = detail.getClick_url();
		if(click == null){
			click = new ArrayList<String>();
		}*/
		List<String> click = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(detail.getClick_url())){
			for(String url:detail.getClick_url()){
				String formatUrl=this.format(url);
			
				if(StringUtils.isNotEmpty(formatUrl)&&!formatUrl.equals(url)){
					action.setLinkurl_type(1);
				}
				click.add(formatUrl);
			}
			
		}
		if(detail.getInst_downstart_url()!=null){//下载开始放在点击上报中
			actType=ACTION_APP;
			click.addAll(detail.getInst_downstart_url());
		}
		
		map.put(CLICK, click);
		// 曝光监测
		List<String> urls = detail.getImpr_url();
		if(urls == null){
			urls = new ArrayList<String>();
		}
		map.put(SHOW, urls);
		// app下载监控
		urls = detail.getInst_downsucc_url();//下载成功
		if(urls != null){
			actType=ACTION_APP;
			map.put(DOWNLOAD, urls);
		}
		
		
		// app安装监控
		urls = detail.getInst_installstart_url();//开始安装
		if(urls != null){
			actType=ACTION_APP;
			map.put(INSTALL, urls);
		}
		// app激活监控
		urls = detail.getInst_installsucc_url();//安装结束上报放在激活中
		if(urls != null){
			actType=ACTION_APP;
			map.put(ACTIVE, urls);
		}
		content.setThirdReportLinks(map);
		action.setType(actType);
		content.setMutiAction(Collections.singletonList(action));
		
		recomReply.setAd_content(content);
		return recomReply;
//		return null;
	}
	
	private AdRecomReply parseVideoAd(XunfeiVideoAd response){
		
		// 返回对象
		AdRecomReply recomReply = new AdRecomReply();
		AdMutiAction action = new AdMutiAction();
		recomReply.setStatus(status);
		
		// 广告内容
		AdContent content = new AdContent();
		content.setMarketTitle(defTitle);
		//content.setContent("");
		//content.setAdId(InvenoIdGenerator.genThirdDspId(SystemContext.getDynamicPropertyHandler().getInt(ProxyConstants.PROXY_SERVER_NODE_INDEX,100)));

		// 视频地址
		AdImg img = new AdImg();
		img.setSrc(response.getUrl());
		List<AdImg> imgs = new ArrayList<AdImg>();
		imgs.add(img);
		content.setImglist(imgs);
		content.setLinkurl(response.getLanding_url());
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		// 点击监测
		List<String> click = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(response.getClick_url())){
			for(String url:response.getClick_url()){
				String formatUrl=this.format(url);
				click.add(formatUrl);
				if(StringUtils.isNotEmpty(formatUrl)&&!formatUrl.equals(url)){
					action.setLinkurl_type(1);
				}
			}
			
		}
		map.put(CLICK, click);
		// 曝光监测
		List<String> show = response.getImpr_url();
		if(show != null){
			show = new ArrayList<String>();
		}
		map.put(SHOW, show);
		content.setThirdReportLinks(map);
		// 类型
		// 内容类型1表示链接推广,2表示应用推广,3未使用 4表示电话推广
		action.setType(ACTION_WEB);
		action.setLinkurl(response.getLanding_url());
		List<AdMutiAction> actions = new ArrayList<AdMutiAction>();
		actions.add(action);
		content.setMutiAction(actions);
		return recomReply;
	}
	public XunfeiAdPuller getXunfeiAdPuller() {
		return XunfeiAdPuller;
	}

	public void setXunfeiAdPuller(XunfeiAdPuller xunfeiAdPuller) {
		XunfeiAdPuller = xunfeiAdPuller;
	}
	private  String format(String str){
		String format= str.replaceAll("IT_CLK_PNT_DOWN_X", "%%DOWNX%%").replaceAll("IT_CLK_PNT_DOWN_Y", "%%DOWNY%%")
				.replaceAll("IT_CLK_PNT_UP_X", "%%UPX%%").replaceAll("IT_CLK_PNT_UP_Y", "%%UPY%%");

		return format;
	}

}
